// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "DBManager/Repository/HDF5/Input/Design/TOMVARRepository.h"

#include "DBManager/Repository/HDF5/Base/HDF5RepositoryMacro.h"

HDF5_REG_REPOSITORY (TOMVARRepository)

using namespace SG::DBManager::HDF5;
using namespace SG::DataStructure;
using namespace SG::DataStructure::FEM;
using namespace SG::DataStructure::Common;

// 构造函数实现
TOMVARRepository::TOMVARRepository (HDF5Database& database) : SG::DBManager::HDF5::MainlyRepositoryBase<MainStruct> (database)
{}

void TOMVARRepository::InitialDatasetInfo ()
{
    RegisterTableInfo<SG::DataStructure::Common::Id> ("/OWN/INDEX/INPUT/DESIGN/TOMVAR", IndexDataset);
    RegisterTableInfo<NasMainStruct> ("/SG/INPUT/DESIGN/TOMVAR/IDENTITY", MainDataset);
    RegisterTableInfo<SubStructDIS> ("/SG/INPUT/DESIGN/TOMVAR/DISCRETE", SubDataset_DIS);
    RegisterTableInfo<SubStructSYM> ("/SG/INPUT/DESIGN/TOMVAR/SYMPLANE", SubDataset_SYM);
    RegisterTableInfo<SubStructTOM> ("/SG/INPUT/DESIGN/TOMVAR/TOMVARID", SubDataset_TOM);
}

void TOMVARRepository::DumpWriteCahce ()
{
    auto& writeStorage = this->GetMainCache ().m_writeStorage;

    // 1. flag设置为无顺序
    GetMainDatasetInfo ().SetIsSequential (false);

    // 主表数据
    std::vector<NasMainStruct> IDENTITYData{};
    // 附表数据
    std::vector<SubStructDIS> subDataDIS;
    std::vector<SubStructSYM> subDataSYM;
    std::vector<SubStructTOM> subDataTOM;

    // 2. 转换为nastran格式数据
    OwnToNastran (writeStorage, IDENTITYData, subDataDIS, subDataSYM, subDataTOM);

    // 3. 写出数据至文件
    WriteData (MainDataset, IDENTITYData);
    WriteData (SubDataset_DIS, subDataDIS);
    WriteData (SubDataset_SYM, subDataSYM);
    WriteData (SubDataset_TOM, subDataTOM);

    // 4. 更新Index表
    this->WriteIndexData (this->GetIndexDatasetInfo (), writeStorage);

    // 5. 清空缓存
    writeStorage.clear ();
}

std::vector<TOMVARRepository::DataType>*  TOMVARRepository::LoadReadCache (std::size_t loadIndex)
{
    // 1. 读取范围内主表数据
    std::vector<NasMainStruct> IDENTITYData;
    LoadMainMetadata (loadIndex, IDENTITYData);

    if (IDENTITYData.empty ())
    {
        return nullptr;
    }

    // 2. 读取范围内附表数据
    std::vector<SubStructDIS> subDataDIS;
    std::vector<SubStructSYM> subDataSYM;
    std::vector<SubStructTOM> subDataTOM;

    LoadSecondaryMetadata (IDENTITYData, DIS_POS, DIS_LEN, SubDataset_DIS, subDataDIS);
    LoadSecondaryMetadata (IDENTITYData, SYM_POS, SYM_LEN, SubDataset_SYM, subDataSYM);
    LoadSecondaryMetadata (IDENTITYData, TOM_POS, TOM_LEN, SubDataset_TOM, subDataTOM);

    // 3. 将数据转换为自己的格式放入缓存
    auto* cacheVector = m_cacheHelper.LookupOrCreateVector<DataType> (GetMainCache ().m_readCacheKey, IDENTITYData.size ());
    NastranToOwn (IDENTITYData, subDataDIS, subDataSYM, subDataTOM, *cacheVector);
    return cacheVector;
}

void TOMVARRepository::SortData ()
{
    // 1. 读取主表数据
    std::vector<NasMainStruct> IDENTITYData;
    GetDataset (MainDataset).read (IDENTITYData);

    if (IDENTITYData.empty ())
    {
        GetMainDatasetInfo ().SetIsSequential (true);
        return;
    }

    // 2. 读取附表数据
    std::vector<SubStructDIS> subDataDIS;
    std::vector<SubStructSYM> subDataSYM;
    std::vector<SubStructTOM> subDataTOM;

    GetDataset (SubDataset_DIS).read (subDataDIS);
    GetDataset (SubDataset_SYM).read (subDataSYM);
    GetDataset (SubDataset_TOM).read (subDataTOM);

    // 3. 将所有数据转换
    std::vector<MainStruct> AllData{};
    NastranToOwn (IDENTITYData, subDataDIS, subDataSYM, subDataTOM, AllData);

    // 4. 排序
    std::sort (AllData.begin (), AllData.end ());

    // 5. 转换回nastran格式
    OwnToNastran (AllData, IDENTITYData, subDataDIS, subDataSYM, subDataTOM, true);

    // 6. 写出主表数据至文件
    GetDataset (MainDataset).write (IDENTITYData);
    // 7. 写出附表数据至文件
    GetDataset (SubDataset_DIS).write (subDataDIS);
    GetDataset (SubDataset_SYM).write (subDataSYM);
    GetDataset (SubDataset_TOM).write (subDataTOM);

    // 8. 重写索引
    RewriteIndexData (AllData);

    // 9. 设置为已顺序
    GetMainDatasetInfo ().SetIsSequential (true);
}

std::vector<TOMVARRepository::MainStruct> TOMVARRepository::GetAllData ()
{
    Sort ();

    std::vector<MainStruct> result;

    std::vector<NasMainStruct> IDENTITYData;
    GetDataset (MainDataset).read (IDENTITYData);

    if (IDENTITYData.empty ())
    {
        return result;
    }

    std::vector<SubStructDIS> subDataDIS;
    std::vector<SubStructSYM> subDataSYM;
    std::vector<SubStructTOM> subDataTOM;

    GetDataset (SubDataset_DIS).read (subDataDIS);
    GetDataset (SubDataset_SYM).read (subDataSYM);
    GetDataset (SubDataset_TOM).read (subDataTOM);

    // 将所有数据转换
    NastranToOwn (IDENTITYData, subDataDIS, subDataSYM, subDataTOM, result);

    return result;
}

void TOMVARRepository::OwnToNastran (std::vector<MainStruct>&         own,
                                     std::vector<NasMainStruct>& _OUT IDENTITYData,
                                     std::vector<SubStructDIS>& _OUT  subDataDIS,
                                     std::vector<SubStructSYM>& _OUT  subDataSYM,
                                     std::vector<SubStructTOM>& _OUT  subDataTOM,

                                     bool isSort)
{
    subDataDIS.clear ();
    subDataSYM.clear ();
    subDataTOM.clear ();

    IDENTITYData.clear ();
    IDENTITYData.reserve (own.size ());

    // 获取已有数据条数，主要是放在主表的POS字段
    // 如果是重新排序的时候，Pos都是从0 开始的
    size_t countDIS = isSort ? 0 : this->GetDatasetInfo (SubDataset_DIS).GetRowCount ();
    size_t countSYM = isSort ? 0 : this->GetDatasetInfo (SubDataset_SYM).GetRowCount ();
    size_t countTOM = isSort ? 0 : this->GetDatasetInfo (SubDataset_TOM).GetRowCount ();

    // OwnIdent 代表咱们自己的数据结构
    // NasIdent 代表nastran的数据结构
    for (auto& OwnIdent : own)
    {
        // 写入附表
        subDataDIS.insert (subDataDIS.end (), OwnIdent.m_DISCRETEList.begin (), OwnIdent.m_DISCRETEList.end ());
        subDataSYM.insert (subDataSYM.end (), OwnIdent.m_SYMPLANEList.begin (), OwnIdent.m_SYMPLANEList.end ());
        subDataTOM.insert (subDataTOM.end (), OwnIdent.m_TOMVARIDList.begin (), OwnIdent.m_TOMVARIDList.end ());

        const size_t lenDIS = OwnIdent.m_DISCRETEList.size ();
        const size_t lenSYM = OwnIdent.m_SYMPLANEList.size ();
        const size_t lenTOM = OwnIdent.m_TOMVARIDList.size ();

        // 写入IDENTITY
        NasMainStruct NasIdent{};

        NasIdent.TOMID = OwnIdent.m_id;
        memcpy (NasIdent.PTYPE, OwnIdent.m_PTYPE, 8);
        NasIdent.PID = OwnIdent.m_pId;
        NasIdent.FID = OwnIdent.m_FID;
        memcpy (NasIdent.PNAME, OwnIdent.m_PNAME, 8);
        NasIdent.XINIT     = OwnIdent.m_XINIT;
        NasIdent.XLB       = OwnIdent.m_XLB;
        NasIdent.XUB       = OwnIdent.m_XUB;
        NasIdent.DELXV     = OwnIdent.m_DELXV;
        NasIdent.DOMAIN_ID = OwnIdent.m_domainId;

        NasIdent.DIS_POS = static_cast<I64> (countDIS);
        NasIdent.SYM_POS = static_cast<I64> (countSYM);
        NasIdent.TOM_POS = static_cast<I64> (countTOM);

        NasIdent.DIS_LEN = static_cast<I64> (lenDIS);
        NasIdent.SYM_LEN = static_cast<I64> (lenSYM);
        NasIdent.TOM_LEN = static_cast<I64> (lenTOM);

        IDENTITYData.emplace_back (NasIdent);

        countDIS += lenDIS;
        countSYM += lenSYM;
        countTOM += lenTOM;
    }
}

void TOMVARRepository::NastranToOwn (std::vector<NasMainStruct>& IDENTITYData,
                                     std::vector<SubStructDIS>&  subDataDIS,
                                     std::vector<SubStructSYM>&  subDataSYM,
                                     std::vector<SubStructTOM>&  subDataTOM,

                                     std::vector<MainStruct>& _OUT own)
{
    own.clear ();
    own.reserve (IDENTITYData.size ());

    // 代表初始的Index 位置,
    // 因为数据有可能是截取了附表的一部分，所有主表中根据POS找的时候需要对应一下，
    // 比如第一个主表数据中POS字段为10000， 附表的vector的数据
    // 就是从附表中的第10000个开始对应的 也就是Index==0的
    // const I64 index = IDENTITYData[0].POS;

    MainStruct const tempown;
    own.resize (IDENTITYData.size (), tempown);

    for (size_t i = 0; i < IDENTITYData.size (); i++)
    {
        auto& OwnIdent = own[i];
        auto& NasIdent = IDENTITYData[i];

        OwnIdent.m_id = NasIdent.TOMID;
        memcpy (OwnIdent.m_PTYPE, NasIdent.PTYPE, 8);
        OwnIdent.m_pId = NasIdent.PID;
        OwnIdent.m_FID = NasIdent.FID;
        memcpy (OwnIdent.m_PNAME, NasIdent.PNAME, 8);
        OwnIdent.m_XINIT    = NasIdent.XINIT;
        OwnIdent.m_XLB      = NasIdent.XLB;
        OwnIdent.m_XUB      = NasIdent.XUB;
        OwnIdent.m_DELXV    = NasIdent.DELXV;
        OwnIdent.m_domainId = NasIdent.DOMAIN_ID;

        if (NasIdent.DIS_LEN != 0)
        {
            OwnIdent.m_DISCRETEList.assign (subDataDIS.begin () + NasIdent.DIS_POS - IDENTITYData[0].DIS_POS,
                                            subDataDIS.begin () + NasIdent.DIS_POS + NasIdent.DIS_LEN - IDENTITYData[0].DIS_POS);
        }
        if (NasIdent.SYM_LEN != 0)
        {
            OwnIdent.m_SYMPLANEList.assign (subDataSYM.begin () + NasIdent.SYM_POS - IDENTITYData[0].SYM_POS,
                                            subDataSYM.begin () + NasIdent.SYM_POS + NasIdent.SYM_LEN - IDENTITYData[0].SYM_POS);
        }
        if (NasIdent.TOM_LEN != 0)
        {
            OwnIdent.m_TOMVARIDList.assign (subDataTOM.begin () + NasIdent.TOM_POS - IDENTITYData[0].TOM_POS,
                                            subDataTOM.begin () + NasIdent.TOM_POS + NasIdent.TOM_LEN - IDENTITYData[0].TOM_POS);
        }
    }
}
